<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Models\Doumvip\WkssDomain;

class WkApi
{
    /* @var $httpClient HttpClient */
    private $httpClient = null;

    private $client_id = 'c8975016-e6b4-46ab-b134-0e7a82c718ae';
    private $client_secret = 'uhYiXsmRhASigDpkCo3PKtu6TwnGR4Oz_ObdRgZfHTk=';
    private $domain = 'https://dou.ugh5.cn';
    private $access_token = '';

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getChannel()
    {
        return [
            ['id' => 1, 'label' => '频道', 'list' =>
                array_column(WkssDomain::find([
                    'conditions' => 'status = 1 and type = 5',
                ])->toArray(), 'name')
            ]
        ];
    }
    public function getTags()
    {
        return [
            1 => ['id' => 1, 'label' => '短视频推广', 'type' => 0],
            2 => ['id' => 2, 'label' => '截流','type' => 1],
            3 => ['id' => 3, 'label' => '店铺/推广','type' => 2],
        ];
    }
    public function getPlatforms()
    {
        return [
            ['value' => 1, 'text' => 'Bilibili'],
            ['value' => 2, 'text' => '小红书'],
            ['value' => 3, 'text' => '视频号'],
            ['value' => 4, 'text' => ' 快手'],
            ['value' => 5, 'text' => '微博'],
            ['value' => 6, 'text' => '知乎'],
            ['value' => 7, 'text' => ' 百家号'],
            ['value' => 8, 'text' => 'QQ短视频'],
            ['value' => 10,'text' => 'Facebook'],
            ['value' => 11,'text' => 'Intagram'],
            ['value' => 12,'text' => 'TikTok'],
            ['value' => 999,'text' => '网店', 'is_api' => false],
        ];
    }

    public function getAccessToken()
    {
        return $this->cacheClass->get(md5('access_token_' . $this->client_id));
    }

    public function setAccessToken($access_token, $expires = 3600)
    {
        $this->cacheClass->set(md5('access_token_' . $this->client_id), $access_token, $expires);
    }

    public function getHeader()
    {
        return [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $this->getAccessToken(),
        ];
    }
    public function checkAuth()
    {
        $access_token = $this->getAccessToken();

        if (!empty($access_token)) {
            return true;
        }

        $url = $this->domain . '/openapi/marketer/auth/access_token';

        $body = [
            'GrantType' => 'client_credentials',
            'ClientID' => $this->client_id,
            'ClientSecret' => $this->client_secret
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, ['Content-Type' => 'application/json']);

        $json = json_decode($response->getBody()->getContents(), true);
        $this->logger($json, $body);
        if (isset($json['Data']['AccessToken'])) {
            $this->setAccessToken($json['Data']['AccessToken'], $json['Data']['ExpiresIn'] - 200);
            return true;
        }

        return false;
    }

    private function logger($json, $body = [])
    {
        Di::getDefault()->get('logger')->info("wkapi:" . (is_array($json) ? json_encode($json) : $json));
        if (!empty($body)) {
            Di::getDefault()->get('logger')->info("wkapi_body:" . (is_array($body) ? json_encode($body) : $body));
        }
    }

    public function createMediaAccount($MediaPlatform, $name, $homeUrl)
    {
        if (!$this->checkAuth()) {
            return false;
        }

        $url = $this->domain . '/openapi/marketer/media_account/create';

        $body = [
            'AccountList' => [
                ['MediaPlatform' => $MediaPlatform, 'Name' => $name, 'URL' => $homeUrl]
            ]
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        $this->logger($json,$body);

        if (isset($json['Data']['List'][0]['Status']) && $json['Data']['List'][0]['Status'] == 1) {
            return $json['Data']['List'][0]['ID'];
        } else {
            throw new Exception(9999, $json['Data']['AddResultList'][0]['Msg']);
        }
    }

    public function applyKeyword($accountId, $tag, $keyword)
    {
        if (!$this->checkAuth()) {
            return false;
        }

        $url = $this->domain . '/openapi/marketer/search_word/create';

        $body = [
            'TaskClaimType' => 4,
            'TaskId' => 16589314,
            'StarSearchWordClaimList' => [
                [
                    "SearchWord" => "$keyword",
                    "MediaAccountID" => $accountId,
                    'Tag' => intval($tag)
                ],
            ]
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        $this->logger($json,$body);

        if (isset($json['Data']['StarSearchWordResultList'][0]['TaskOrderID'])) {
            return $json['Data']['StarSearchWordResultList'][0]['TaskOrderID'];
        } else {
            throw new Exception(9999, $json['Data']['StarSearchWordResultList'][0]['Msg']);
        }
    }

    public function getKeywordStatus($keyword)
    {
        if (!$this->checkAuth()) {
            return false;
        }

        $url = $this->domain . '/openapi/marketer/search_word/list';

        $body = [
            'SearchWord' => $keyword,
            'PageNo' => 1,
            'PageSize' => 10,

        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        $this->logger($json,$body);

        if (isset($json['Data']["List"])) {
           foreach ($json['Data']["List"] as $item) {
              if ($item['SearchWordInfo']['SearchWord'] === $keyword) {
                  return [$item['SearchWordInfo']['SearchWordStatus'], $item['SearchWordInfo']];
              }
           }
        }

        return [false, []];
    }

    public function addContent($taskOrderId, $link)
    {
        if (!$this->checkAuth()) {
            return false;
        }

        $url = $this->domain . '/openapi/marketer/search_word/add_content';

        $body = [
            'TaskOrderID' => $taskOrderId,
            'ContentURLs' => [$link],
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        $this->logger($json,$body);

        if (isset($json['Data']["ResultList"][0]['Code']) && $json['Data']["ResultList"][0]['Code'] == 0) {
             return true;
        } else {
            throw new Exception(9999, $json['Data']["ResultList"][0]['Msg'] ?? "系统错误");
        }

        return false;
    }
}
